package org.example.rocketmqstudy.producer;

import io.netty.channel.DefaultChannelId;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ScheduledMessageProducer {
    public static void main(String[] args) throws Exception {
        DefaultChannelId.newInstance(); // 解决 RemotingTimeoutException: invokeSync call timeout 异常

        // Instantiate a producer to send scheduled messages
        DefaultMQProducer producer = new DefaultMQProducer("my-producer-group");
        producer.setNamesrvAddr("8.138.36.56:9876");
        // Launch producer
        producer.start();
        int totalMessagesToSend = 3;
        for (int i = 0; i < totalMessagesToSend; i++) {
            Message message = new Message("test-scheduled-msg", ("Hello scheduled message " + i).getBytes());
            // This message will be delivered to consumer 10 seconds later.
            message.setDelayTimeLevel(4);
            // Send the message
            producer.send(message);

            String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            System.out.printf("%s [%s] Send New Message: %s %n", now, Thread.currentThread().getName(), new String(message.getBody()));
            Thread.sleep(5000); // 每发一条，间隔 5 秒
        }

        // Shutdown producer after use.
        producer.shutdown();
    }
}